<!-- 综合查询-文档信息 -->
<template>
  <el-container>
    <el-main class="mainDetails">
      <div class="documentInfo">
        <SearchPanel title="查询条件">
          <div ref="queryFormBox" class="search-flex-box">
            <MyForm
              ref="formRef"
              v-model="queryParams"
              :form-option="formOption"
              :select-list="dicLists"
              class="myForm"
              @handleEvent="handleEvent"
            />
            <div class="searchBtn">
              <el-button type="primary" class="pms-button-primary" @click="doSearch">查询</el-button>
              <!-- <el-button size="mini" class="pms-button" @click="resetSearch">重置</el-button> -->
            </div>
          </div>
        </SearchPanel>
        <SearchList title="查询结果" style="margin-top: 16px">
          <template #header-btn>
            <BtnConfig ref="btnConfigRef" :btn-configs="btnOption" @propClick="btnClick" />
          </template>
          <template #body>
            <MyTable
              id="fileId"
              ref="myTableRef"
              :table-data="tableData"
              :columns="colOption"
              :col-option-enum="dicLists"
            >
              <template #fileName="{ scope }">
                <el-button type="text" @click="preview(scope)">{{ scope.fileName }}</el-button>
              </template>
            </MyTable>
            <pagination
              v-if="pageParam.total > 10"
              :total="pageParam.total"
              :page.sync="pageParam.pageNum"
              :limit.sync="pageParam.pageSize"
              @pagination="doSearch"
            />
          </template>
        </SearchList>
        <!-- 文件预览 -->
        <el-dialog
          v-if="dialogFileView"
          v-dialogDrags
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          title="预览"
          height="60%"
          width="60%"
          class="pms-dialog"
          :visible.sync="dialogFileView"
        >
          <div class="signatoryPre">
            <FilePreview ref="filePreviewRef" class="filePreviewClass" :file-obj="fileObj" />
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button size="small" @click="dialogFileView = false">取 消</el-button>
          </div>
        </el-dialog>
        <!-- 图片全览 -->
        <el-dialog
          v-if="pictureShow"
          :append-to-body="true"
          :modal-append-to-body="true"
          :modal="true"
          :close-on-click-modal="false"
          title="图片全览"
          height="60%"
          width="70%"
          class="pms-dialog"
          :visible.sync="pictureShow"
        >
          <PicturePage :picture-show="pictureShow" :prj-params="this.queryParams" />
        </el-dialog>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import axios from 'axios'
import MyForm from '@/components/basic/myForm'
import SearchPanel from '@/components/basic/SearchPanel'
import SearchList from '@/components/basic/SearchList'
import MyTable from '@/components/basic/myTable'
import BtnConfig from '@/components/basic/btnConfig.vue'
import SysConst from '@/common/const'
import FilePreview from '@/components/business/filePreview.vue'
import { getQueryObject, msgInfoEl, downloadFileFun } from '@/utils' // singleDownload, mulDownload
import { getNodeInfoApi } from '@/api/attachManagement/attachments/attachmentDetails'
import { getSignFlowDocUrlsApi } from '@/api/attachManagement/electronicSign/electronicSignature'
import {
    getPrjStageApi,
    getPrjFileInfoApi,
    batchDownloadApi, // 批量下载
    downloadApi, getPreviewFile, getWPSToken, querySuffix // 单个文件下载
} from '@/api/attachmentInfo'
import {
    formOption,
    colOption,
    btnOption,
    fileModes
} from '.'
import $ from 'jquery'
const Base64 = require('js-base64').Base64
import PicturePage from './picturePage.vue'
export default {
    name: 'DocumentInfo',
    components: {
        MyForm,
        SearchPanel,
        SearchList,
        MyTable,
        FilePreview,
        BtnConfig,
        PicturePage
    },
    data() {
        return {
            formOption, // 查询条件配置
            tableData: [], // 列表数据
            colOption, // 列表表头配置
            btnOption, // 列表操作按钮配置
            queryParams: {}, // 查询条件数据
            prjParams: {}, // 页面路由参数集
            dicLists: {}, // 字典数据集合
            dialogFileView: false, // 文件预览
            fileObj: {}, // 预览文件地址
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            wpsToken: '',
            pictureShow: false,
            previewObj:{},
        }
    },
    created() {
        this.getDictData()
        const { prjId } = getQueryObject()
        this.prjParams = {
            prjId // 项目id
        }
        this.getPrjStage()
        this.doSearch()
        this.getToken()
        this.querySuffix()
    },
    methods: {
        querySuffix() {
            querySuffix().then((res) => {
                if (+res.code === 200) {
                    this.previewObj = res.data
                }
            })
        },
        // 全览功能
        picturePanorama() {
            this.pictureShow = true
        },
        getToken() {
            getWPSToken().then((res) => {
                if (+res.code === 200) {
                    this.wpsToken = res.data
                }
            })
        },
        // 查询
        doSearch(item) {
            const params = {
                prjId: this.prjParams.prjId,
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                ...this.queryParams
            }
            getPrjFileInfoApi(params).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                this.tableData = res.data.records
                this.pageParam.total = res.data?.total || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
            })
        },
        // 当父组件接收到了子组件this.$emit的通知后就会执行这个方法来接收子组件点击传递过来的数据
        btnClick(fun, row) {
            this[fun](row)
        },
        // 下载
        download(row) {
            console.log(row, '下载--row')
            const fileDownloadNo = row.find(item => item.fileId === '' || item.fileId === null || item.fileId === undefined) || {}
            if (JSON.stringify(fileDownloadNo) !== '{}') {
                return msgInfoEl({
                    type: 'info',
                    message: `当前选择范围中存在未上传文件，请上传或取消勾选该文件再进行下载`
                })
            }
            const fileName = row.length > 1 ? '附件信息.zip' : row[0].fileName
            // 单个文件下载时的参数
            const params = {
                fileId: row[0].fileId,
                fileName: row[0].fileName
            }
            // 多个文件下载时的参数
            const batchParams = row.map(item => ({
                fileId: item.fileId,
                fileName: item.fileName
            }))
            if (row.length > 1) {
                // mulDownload(row, fileName)
                // 批量下载
                batchDownloadApi({ fileMap: batchParams }).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            } else {
                // singleDownload(row, fileName)
                // 单个文件下载
                downloadApi(params).then(res => {
                    console.log(res, '下载')
                    downloadFileFun(res, fileName)
                })
            }
        },
        getUserId(){
            let str='';
            if(sessionStorage.getItem('SET_LOGINDATA')){
              str = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')).staffId
            }else if(sessionStorage.getItem('userInfo')){
              str = JSON.parse(sessionStorage.getItem('userInfo')).staffId
            }else{
              console.log('')
            }
            console.log('str',str)
            return str;
        },
        // 预览
        async preview(row) {
            if (row.isSignature === '1') {
                this.getSignFlowDocUrls(row.fileViewId)
                return
            } else {
                const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
                const previewArray = Object.keys(this.previewObj);
                if (previewArray.includes(types)) {
                    const params = {
                        fileId: row.fileId,
                        type: this.previewObj[types],
                        userId: this.getUserId(),
                        token: this.wpsToken
                    }
                    getPreviewFile(params).then((res) => {
                        // if(+res.code===200){
                        //     const newWin = window.open()
                        //     const form = $("<form method='post'></form>")
                        //     form.attr({ action: res.data })
                        //     form.appendTo(newWin.document.body)
                        //     form.submit()
                        // }
                        if (+res.code === 200 && res.data) {
                            window.open(res.data, '_blank')
                        }
                    })
                } else {
                    return msgInfoEl({
                        type: 'info',
                        message: `所选文件不支持预览`
                    })
                }
            }
            // let res = {}
            // const params = {
            //     fileId: row.fileId,
            //     fileName: row.fileName
            // }
            // await downloadApi(params).then(r => {
            //     res = r
            // })
            // const blob = new Blob([res.data], { type: 'application/pdf;charset-UTF-8' })
            // const url = window.URL.createObjectURL(blob)
            // row.filePath = url
            // this.fileObj = {}
            // if (!row.filePath) {
            //     return msgInfoEl({
            //         type: 'info',
            //         message: `所选${row.fileName}文件不支持预览`
            //     })
            // }
            // const types = row.fileName.substring(row.fileName.lastIndexOf('.') + 1)
            // if (['word', 'docx', 'excel', 'xlsx'].includes(types)) {
            //     console.log(types, '12')
            //     window.open(this.$router.resolve({
            //         name: 'FilePreview',
            //         query: {
            //             type: types,
            //             fileSrc: row.filePath
            //         }
            //     }).href, '_blank')
            //     return
            // }
            // if (['pdf'].includes(types)) {
            //     window.open(row.filePath, '_blank')
            //     return
            // }
            // if (['pptx', 'ppt', 'doc', 'xls'].includes(types)) {
            //     // window.open(`${process.env.VUE_APP_BASE_API}preview/onlinePreview?url=${encodeURIComponent(Base64.encode(row.filePath))}`, '_blank')
            //     return msgInfoEl({
            //         type: 'info',
            //         message: `所选文件不支持预览`
            //     })
            // }
            // if (['jpg', 'png', 'jpeg', 'bmp', 'mp3', 'mp4', 'webm', 'ogg', 'aac', 'wav'].includes(types)) {
            //     this.fileObj = {
            //         type: types,
            //         fileSrc: row.filePath
            //     }
            //     this.dialogFileView = true
            // } else if (['txt'].includes(types)) {
            //     axios.get(row.filePath, {
            //         responseType: 'blob',
            //         transformResponse: [
            //             async function(data) {
            //                 // txt转码
            //                 return await new Promise((resolve) => {
            //                     const reader = new FileReader()
            //                     reader.readAsText(data, 'UTF-8') // GBK UTF-8
            //                     reader.onload = () => {
            //                         resolve(reader.result)
            //                     }
            //                 })
            //             }
            //         ]
            //     }).then(res => {
            //         res.data.then((data) => {
            //             this.fileObj = {
            //                 type: types,
            //                 fileSrc: data
            //             }
            //         })
            //     })
            //     this.dialogFileView = true
            // } else {
            //     this.$message.info('不支持预览此文件')
            // }
            // console.log(row, types, '预览')
        },
        // 电子签章预览
        getSignFlowDocUrls(id) {
            getSignFlowDocUrlsApi({ id }).then(res => {
                if (+res.code !== 200) {
                    return Promise.reject(res)
                }
                if (res.data) {
                    // window.open(res.data, '_blank')
                    axios.get(res.data, {
                        responseType: 'blob',
                        cache: true,
                        headers: {
                            'Content-Disposition': 'inline'
                        }
                    }).then(r => {
                            const blob = new Blob([r.data], { type: 'application/pdf;charset-UTF-8' })
                            // const blob = new Blob([r.data], { type: r.headers['content-type'] })
                            const url = window.URL.createObjectURL(blob)
                            window.open(url, '_blank')
                            URL.revokeObjectURL(url) // 释放内存
                    })
                }
            })
        },
        // 重置
        // resetSearch() {
        //     this.$refs.formRef.reset()
        //     this.doSearch({
        //         page: 1,
        //         limit: 10
        //     })
        // },
        // 查询条件事件
        handleEvent(prop, val) {
            if (prop === 'prjStage') {
                this.getPrjNodeName(val)
                this.queryParams.nodeId = ''
            }
        },
        // 获取下拉框数据
        async getDictData() {
            // const arr = ['PROJECT_STAGE']
            // const promises = arr.map(item => getDropdownData(item))
            // const results = await Promise.all(promises)
            // arr.forEach((item, i) => {
            //     this.$set(this.dicLists, item, results[i].data ?? [])
            // })
            this.$set(this.dicLists, 'FILE_MODES', fileModes)
        },
        // 获取项目阶段字典
        async getPrjStage() {
            const res = await getPrjStageApi()
            this.$set(this.dicLists, 'PRO_STAGE', res.data)
        },
        // 获取项目节点字典
        async getPrjNodeName(val) {
            if (!val) {
                return
            }
            const res = await getNodeInfoApi({ prjId: this.prjParams.prjId, prjStage: val ?? '' })
            if (!res.data.length) {
                this.$message.info('此项目阶段下项目节点为空')
            }
            this.$set(this.dicLists, 'PRJ_NODE', res.data)
        }
    }
}
</script>

<style lang="scss" scoped>
.mainDetails {
    padding: 15px 25px 0;
}
.search-flex-box {
    // display: flex;
    // justify-content: space-between;
    height: auto;
}
.searchBtn {
    width: 100px;
    margin-left: auto;
    display: flex;
    margin-top: 4px;
    flex-direction: column;
    .el-button + .el-button {
        margin-left: 0;
        margin-top: 12px;
    }
}
.el-button + .el-button {
    margin-left: 0;
    margin-top: 6px;
}
.el-button--text {
    color: #02A7F0;
}
::v-deep .tnBox {
    padding-right: 10px;
}
.documentInfo {}
</style>
